const {verify} = require("jsonwebtoken");

const COS = require('cos-nodejs-sdk-v5');
const formidable = require("formidable");
let form = new formidable.IncomingForm();//既处理表单，又处理文件上传
form.keepExtensions = true
const { createReadStream } = require("fs");
const {unlinkSync} = require("node:fs");
const cos = new COS({
  SecretId: 'AKIDoRo7LaqXR6Zs0vg8PsBdswnbDagZdl5G', // 推荐使用环境变量获取；用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参考https://cloud.tencent.com/document/product/598/37140
  SecretKey: 'CCzNYXIqBJCpDQSGrGPL3Z4NYXJsDJBs', // 推荐使用环境变量获取；用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指
});

// 把文件上传到腾讯云的 cos
let upload = (filePath) => {
  // 从请求中获取文件
  const file = filePath.file;
  return new Promise((resolve, reject) => {
    cos.putObject({
      Bucket: 'gundam-1253271162',
      Region: 'ap-guangzhou',
      Key: file.originalname,
      StorageClass: 'STANDARD',
      Body:createReadStream(file.path),
      onProgress:(info) => {
        console.log(JSON.stringify(info));
      }
    }, (err, data) => {
      // 删除本地临时文件（可选）
      unlinkSync(file.path);
      resolve(err || data)
    });
  })
}

// 查询存储桶列表
async function getService() {
  const res = await cos.getService();
  console.log(res)
  if (res) {
    console.log(res)
    return {
      code: 200,
      msg: '请求成功',
      data: res
    }
  }
}

// 保存视频到数据库
async function uploadVideo(data) {
  let selectSql = `SELECT * FROM idcardfile WHERE id = ${id}`
  const selectRows = await global.sql(selectSql)
  if (selectRows.status) {
    return {
      code: 200,
      msg: '上传成功',
      data: selectRows.data[0]
    }
  }else {
    return {
      code: 500,
      msg: '上传失败',
      data: null
    }
  }
}

// 保存图片到数据库
async function uploadImg(data) {
  let selectSql = `SELECT * FROM idcardfile WHERE id = ${id}`
  const selectRows = await global.sql(selectSql)
  if (selectRows.status) {
    return {
      code: 200,
      msg: '上传成功',
      data: selectRows.data[0]
    }
  }else {
    return {
      code: 500,
      msg: '上传失败',
      data: null
    }
  }
}

// 通过 id 去查身份证照片
async function getIdCardById(id) {
  let selectSql = `SELECT * FROM idcardfile WHERE id = ${id}`
  const selectRows = await global.sql(selectSql)
  if (selectRows.status) {
    return {
      code: 200,
      msg: '上传成功',
      data: selectRows.data[0]
    }
  }else {
    return {
      code: 500,
      msg: '上传失败',
      data: null
    }
  }
}


// 把身份证图片保存到数据库里面
async function saveIdCard(data) {
  const dateTime = global.commonFun.getNowTime()
  let addSql = `INSERT INTO idcardfile(userId,url,createTime) VALUES(?,?,?)`
  const addSqlParams = [data.userId, data.Location, dateTime];
  const addRow = await global.sql(addSql,addSqlParams)
  if (addRow.status) {
    return await getIdCardById(addRow.data.insertId)
  }else {
    return {
      code: 500,
      msg: '上传失败',
      data: null
    }
  }
}


exports.uploadImg = uploadImg
exports.uploadVideo = uploadVideo
exports.getService = getService
exports.saveIdCard = saveIdCard
exports.getIdCardById = getIdCardById
exports.upload = upload
